package com.qingzhuge.manager.security.handler;

import cn.hutool.http.HttpStatus;
import com.google.gson.Gson;
import com.qingzhuge.autoconfigure.QingTingProperties;
import com.qingzhuge.common.HttpCode;
import com.qingzhuge.dto.response.ResponseBodyDto;
import com.qingzhuge.manager.security.rest.AuthenticationInfo;
import com.qingzhuge.manager.dto.SecurityUser;
import com.qingzhuge.manager.security.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zeroxiao
 * @date 2019/9/10 20:43
 * 认证成功事件处理器
 */
@Slf4j
public class LoginSuccessEventHandler implements AuthenticationSuccessHandler {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private QingTingProperties properties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        log.debug("登录成功");
        response.setCharacterEncoding("UTF8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        ResponseBodyDto<AuthenticationInfo> result = new ResponseBodyDto<>();
        result.setCode(HttpCode.LOGIN_SUCCESS.value());
        result.setMessage(HttpCode.LOGIN_SUCCESS.message());
        Object principal = authentication.getPrincipal();
        SecurityUser securityUser = (SecurityUser) principal;
        String token = null;
        if (properties.getSecurity().isOpenJwt()) {
            // 生成令牌
            token = jwtTokenUtil.createToken(securityUser);
        }
        // 返回
        result.setData(new AuthenticationInfo(token, securityUser));
        response.setStatus(HttpStatus.HTTP_OK);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(new Gson().toJson(result));
    }
}